package com.demo.project.dao;

import com.demo.annotation.Component;
import com.demo.project.entity.Team;
import com.demo.project.utils.StringUtils;
import lombok.Data;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@Component
public class TeamDataServer {
    private Map<String, Team> teamMap = new HashMap<>(); // teamId and team
    private  Map<String,String> teamInfoMap = new HashMap<>();// teamInfoId  teamId

    public List<PersistentConfig> getPersistenceConfigs(){
        List<PersistentConfig> configs = new ArrayList<>();
        PersistentConfig teamMapConfig = new PersistentConfig(PersistenceUtil.basePath+ File.separator+"teamMap.txt",String.class,Team.class,"teamMap");
        PersistentConfig teamInfoMapConfig = new PersistentConfig (PersistenceUtil.basePath+File.separator+"teamInfoMap.txt",String.class,String.class,"teamInfoMap");
        configs.add(teamInfoMapConfig);
        configs.add(teamMapConfig);
        return configs;
    }
    public String addTeamInfo(Team team){
        String s = StringUtils.generateTeamId(team);
        teamInfoMap.put(s,team.getId());
        return s;
    }

    /**
     * 通过info 的信息来得到符合条件的Team 的id值，可以在team Map中找到
     * @param info
     * @return
     */
    public List<String> getTeamIdByInfo(String info){
        List<String> teamIds = new ArrayList<>();
        teamInfoMap.forEach((k,v)->{
            if(k.contains(info)){
                teamIds.add(v);
            }
        });
        return teamIds;
    }

    /**
     * 创建队伍，要传入team信息，team的id是 随机创建的，创建成功后，返回teamInfoId
     * @param team
     * @return
     */

    public String createTeam(Team team){

        if(team!=null){
            team.participate(team.getInitiatorId());
            team.setNeedNumber(team.getTotalTeamNumber()-1);
            teamMap.put(team.getId(),team);
            addTeamInfo(team);

            return team.getId();
        }
        return null;
    }
    public boolean deleteTeam(String teamId){
        Team remove = this.teamMap.remove(teamId);
        if(remove==null){
            return false;
        }
        String s = StringUtils.generateTeamId(remove);
        teamInfoMap.remove(s);
        return (remove==null)?false:true;
    }
    public Team search(String teamId){
        return this.teamMap.get(teamId);
    }
    public boolean updateTeam(Team team){
        this.teamMap.replace(team.getId(),team);//替换 team
        return true;
    }
}
